package pl.com.hme.kody.pocztowe.parser;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import pl.com.hme.kody.pocztowe.R;
import pl.com.hme.kody.pocztowe.data.PointOfInterest;
import pl.com.hme.kody.pocztowe.data.SearchResults;
import pl.com.hme.kody.pocztowe.exception.ParserException;
import android.content.Context;

public class PnaJsonParser {
	@SuppressWarnings("unused")
	private static final String TAG = "PnaJsonParser";

	public static SearchResults parseJsonString(Context context,String jsonString) throws ParserException {
		SearchResults searchResults = new SearchResults();

		try {
			JSONObject jsonPnaData = (new JSONObject(jsonString)).getJSONObject("ServicePna");
			if (jsonPnaData.getJSONObject("get_postal_code_of_place_street_community_id").getString("status").equals(
					"success")) {
				jsonPnaData = jsonPnaData.getJSONObject("get_postal_code_of_place_street_community_id");
				jsonPnaData.remove("status");

				JSONArray jsonArray = jsonPnaData.toJSONArray(jsonPnaData.names());

				if (jsonArray != null) {
					int length = jsonArray.length();

					for (int i = 0; i < length; i++) {
						JSONObject jsonPoi = jsonArray.getJSONObject(i);

						PointOfInterest poi = new PointOfInterest();

						poi.setBorough(jsonPoi.getString("community_name"));
						poi.setCode(jsonPoi.getString("postal_code"));
						poi.setDistrict(jsonPoi.getString("district_name"));
						poi.setLocality(jsonPoi.getString("place"));
						poi.setProvince(jsonPoi.getString("province_name"));
						poi.setStreet(jsonPoi.getString("street_name"));
						poi.setStreetNumbers(jsonPoi.getString("street_number"));

						searchResults.addPoi(poi);
					}
				}
			}
		} catch (JSONException e) {
			throw new ParserException(context.getString(R.string.error_parsing_xml), e);
		}

		return searchResults;
	}
}
